package eventplanner.ejb.interceptors;

import eventplanner.ejb.Session;
import eventplanner.ejb.exceptions.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import java.io.Serializable;

/**
 * This interceptor checks if the user is logged in. If not then it will throw a <code>UnauthorizedException</code>.
 * There is a whitelist for methods which don't require authentication.
 */
public class LoginSecurityInterceptor implements Serializable {

	private static final Logger LOG = LoggerFactory.getLogger(LoginSecurityInterceptor.class);

	@Inject
	private Session session;

	/**
	 * This method checks if the user is logged in
	 *
	 * @param context The context of the invocation
	 * @return the result of the method
	 * @throws Exception an UnauthorizedException if you user is not logged in but should be
	 */
	@AroundInvoke
	public Object transformReturn(InvocationContext context) throws Exception {

		LOG.info("Method intercepted, name='{}' loggedin {} name '{}'",
				new Object[]{context.getMethod().getName(), session.isLoggedIn(), session.getUser()});

		if (!session.isLoggedIn()) {
			throw new UnauthorizedException();
		}

		return context.proceed();
	}
}
